<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        当前位置：首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>宠物管理</el-breadcrumb-item>
      <el-breadcrumb-item>宠物防丢码管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索区 -->
      <el-form
        ref="searchFormRef"
        :inline="true"
        :model="queryInfo.query"
        size="mini"
      >
        <el-form-item style="width: 400px">
          <el-col :span="7">
            <el-form-item prop="date_type">
              <el-select
                v-model="queryInfo.query.date_type"
                placeholder="请选择"
                size="mini"
              >
                <el-option label="生成日期" value="1"></el-option>
                <el-option label="绑定日期" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="start_date">
              <el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="queryInfo.query.start_date"
                size="mini"
                style="width: 125px"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="1">-</el-col>
          <el-col :span="8">
            <el-form-item prop="end_date">
              <el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="queryInfo.query.end_date"
                size="mini"
                style="width: 100%"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryInfo.query.status"
            placeholder="请选择"
            filterable
            size="mini"
            clearable
          >
            <el-option key="2" label="待激活" value="2"> </el-option>
            <el-option key="1" label="已激活" value="1"> </el-option>
            <el-option key="3" label="已失效" value="3"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryInfo.query.keywords"
            placeholder="请输入防丢码编号、用户账号、手机号或联系电话"
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            class="theme-background-color"
            size="mini"
            @click="searchList"
          >
            搜索
          </el-button>
          <el-button size="mini" @click="resetSearchForm"> 重置 </el-button>
        </el-form-item>
      </el-form>

      <!-- 操作区域 -->
      <div>
        <el-button
          icon="el-icon-document-add"
          size="mini"
          @click="batchGenerate"
        >
          批量生成
        </el-button>
        <!-- <el-button icon="el-icon-download" size="mini"> 导出数据 </el-button> -->
      </div>

      <!-- 列表区域 -->
      <el-table :data="list" border stripe>
        <el-table-column label="防丢码编号" prop="plate_no"></el-table-column>
        <el-table-column label="所属用户" prop="user_name"></el-table-column>
        <el-table-column label="用户手机号" prop="phone"></el-table-column>
        <el-table-column label="绑定宠物" prop="pets_name"></el-table-column>
        <el-table-column label="联系电话" prop="user_phone"></el-table-column>
        <el-table-column label="生成时间" prop="create_date"></el-table-column>
        <el-table-column label="绑定时间" prop="bind_time"></el-table-column>
        <el-table-column label="状态" prop="status_str"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-link
              type="danger"
              v-if="scope.row.status == 2"
              @click="deleteData(scope.row)"
            >
              删除
            </el-link>
            &nbsp;
            <el-link
              type="primary"
              v-if="scope.row.status == 2 || scope.row.status == 1"
              @click="downloadImage(scope.row.plate_no)"
            >
              下载
            </el-link>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        query: {
          date_type: '1',
          start_date: '',
          end_date: '',
          status: '',
          keywords: ''
        },
        pagenum: 1,
        pagesize: 20
      },
      list: [],
      total: 0
    }
  },
  created() {
    this.initDate()
    this.getListData()
  },
  methods: {
    initDate() {
      // 默认一个月
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      this.queryInfo.query.start_date = this.getFormatDate(start)
      this.queryInfo.query.end_date = this.getFormatDate(end)
    },
    searchList() {
      this.queryInfo.pagenum = 1
      this.getListData()
    },
    resetSearchForm() {
      this.$refs.searchFormRef.resetFields()
      this.getListData()
    },
    batchGenerate() {
      // 弹框询问是否下架商品
      this.$prompt('请输入数量', '批量生成', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[1-9]\d*$/,
        inputErrorMessage: '格式不正确',
        closeOnClickModal: false
      })
        .then(async ({ value }) => {
          console.log(value)
          this.toGenerate(value)
          this.$message.success('成功生成')
          setTimeout(() => {
            this.getListData()
          }, 200)
        })
        .catch(() => {
          this.$message.info('已取消操作')
        })
      // this.toGenerate()
    },
    async toGenerate(num) {
      // 返回数据重命名为res
      const { data: res } = await this.$http.post(
        '/admin/safe_plate/batchGenerate',
        { count: num }
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
    },
    async getListData() {
      // 返回数据重命名为res
      const { data: res } = await this.$http.post(
        '/admin/safe_plate/list',
        this.queryInfo
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.list = res.data.list
      this.total = res.data.total
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getListData()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getListData()
    },
    deleteData(row) {
      // 弹框询问是否禁用用户
      this.$prompt('确定删除防丢码【' + row.plate_no + '】吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        inputPattern: /^(?!.{500}|^\s*$)/g,
        inputErrorMessage: '请输入删除原因',
        closeOnClickModal: false
      })
        .then(async ({ value }) => {
          console.log(value)
          const { data: res } = await this.$http.post(
            '/admin/safe_plate/delete',
            {
              id: row.id,
              reason: value
            }
          )
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success(res.meta.msg)
          this.getListData()
        })
        .catch(() => {
          this.$message.info('已取消操作')
        })
    },
    async downloadImage(code) {
      const { data: res } = await this.$http.post(
        '/admin/safe_plate/download',
        {
          plate_no: code
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      //   var url =        'http://chongtai.tutaiyangche.com/upload/pages/petCard/welcome/CTT00000004.png'
      this.downloadIamge(res.data, code)
    },
    downloadIamge(imgsrc, name) {
      //下载图片地址和图片名
      var image = new Image()
      // 解决跨域 Canvas 污染问题
      image.setAttribute('crossOrigin', 'anonymous')
      image.onload = function () {
        var canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        var context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height)
        var _dataURL = canvas.toDataURL('image/png') //得到图片的base64编码数据

        var blob_ = dataURLtoBlob(_dataURL) // 用到Blob是因为图片文件过大时，在一部风浏览器上会下载失败，而Blob就不会

        var url = {
          name: name || '图片.png', // 图片名称不需要加.png后缀名
          src: blob_
        }

        if (window.navigator.msSaveOrOpenBlob) {
          // if browser is IE
          navigator.msSaveBlob(url.src, url.name) //filename文件名包括扩展名，下载路径为浏览器默认路径
        } else {
          var link = document.createElement('a')
          link.setAttribute('href', window.URL.createObjectURL(url.src))
          link.setAttribute('download', url.name + '.png')
          document.body.appendChild(link)
          link.click()
        }
      }
      image.src = imgsrc

      function dataURLtoBlob(dataurl) {
        var arr = dataurl.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        return new Blob([u8arr], { type: mime })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.line {
  text-align: center;
}
</style>
